package cdu.sl.aichatdemo.service.impl;


import cdu.sl.aichatdemo.constants.AppConstants;
import cdu.sl.aichatdemo.service.EmailService;
import cdu.sl.aichatdemo.utils.CodeUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.MailSender;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.stereotype.Service;

@Slf4j
@Service
@RequiredArgsConstructor
public class EmailServiceImpl implements EmailService {

    private final MailSender mailSender;

    @Value("${spring.mail.username}")
    private String senderEmail;

    /**
     * 向目标邮箱发起注册验证码
     *
     * @param target 目标邮箱
     * @return 验证码
     */
    @Override
    public String sendVerificationCode(String target, String subject, String content) {
        String verificationCode = CodeUtil.generateAlphaNumericCode();
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(senderEmail);
        message.setTo(target);
        message.setSubject(AppConstants.APP_NAME + subject);
        message.setText(content + ",验证码：" + verificationCode + " \n时效五分钟,如非本人操作,请忽略");

        try {
            mailSender.send(message);
            log.info("验证码已发送至邮箱: {}", target);
            return verificationCode;
        } catch (Exception e) {
            log.error("发送验证码邮件失败: {}", e.getMessage());
            throw new RuntimeException("发送验证码邮件失败");
        }
    }


}
